import * as dayjs from 'dayjs';
import he from 'he';

/**
 * 处理 smslist_source 和 phonebook_source 数据
 * @param {*} data1
 * @param {*} data2
 * @returns 返回处理好后的数据
 */
export const formatData = (data1, data2) => {
    const data = {
        Device_message_list: [],
        Sim_message_list: [],
        Device_message_total: 0,
        SIM_message_total: 0
    };

    // 判断data1、data2是否underfined

    if (typeof data1 !== 'undefined' || typeof data2 !== 'undefined') {
        if (data1 == '') return data;

        let dmlist = [];
        let smlist = [];
        let pblist = [];

        try {
            const n_data1 = JSON.parse(data1);
            console.log('短信传输数据n_data1:', n_data1);
            dmlist = n_data1.Device_message_list;
            smlist = n_data1.Sim_message_list;
            console.log('联系人数据data2:', data2);

            // try {
            //     // data2 == '' ? (pblist = []) : (pblist = JSON.parse(data2).phonebook_list);
            //     data2 == '' ? (pblist = []) : (pblist = JSON.parse(data2));
            // } catch (error) {
            //     console.log('PHONEBOOK JSON ERR =>', error);
            //     pblist = [];
            // }
            console.log('短信传输数据dmlist:', dmlist);
            console.log('短信传输数据smlist:', smlist);
            //console.log('短信传输数据pblist:', pblist);
            const sortdmlist = abilitySort(dmlist, 'number');
            const sortsmlist = abilitySort(smlist, 'number');
            console.log('短信传输数据sortdmlist:', sortdmlist);
            console.log('短信传输数据sortsmlist:', sortsmlist);
            
            // let newdmlist = filterName(sortdmlist, pblist);
            // let newsmlist = filterName(sortsmlist, pblist);

            dmlist.sort((before, after) => new Date(after.date) - new Date(before.date));
            smlist.sort((before, after) => new Date(after.date) - new Date(before.date));
            
            console.log('短信传输数据newsmlist:', smlist);
            console.log('短信传输数据newdmlist:', dmlist);
            return {
                Device_message_list: dmlist,
                Sim_message_list: smlist,
                Device_message_total: dmlist.length,
                SIM_message_total: smlist.length
            };
        } catch (error) {
            console.log('SMS JSON ERR =>', error);
            return data;
        }
    } else {
        return data;
    }
};

/**
 * 根据传入的字段进行分组
 * @param arr 需要分组的数组
 * @param property 分组的字段
 * @returns {*[]} 已分好组的数组
 */
export const abilitySort = (arr, property) => {
    let map = {};

    const data = arr.reduce((acc, obj) => {
        const key = obj.number;
        if (!acc[key]) {
            acc[key] = [];
        }
        acc[key].push(obj);
        return acc;
    }, {});

    for (const key in data) {
        // 去除所有非数字符号
        const number = key.replace(/\D/g, '');

        // 去除前缀0
        const intNumber = String(number.replace(/^0+/, ''));

        // 去除前缀0后，数字仍大于五位时
        if (intNumber.length > 5) {
            // 遍历已经匹配的数据，查看是否已经存在
            const groupKey = Object.keys(map).find((groupKey) => {
                if (groupKey.length > 5) {
                    // 获取号码末尾 短的则获取全部 长的根据短的长度获取
                    const groupNumber = groupKey.slice(-Math.min(groupKey.length, intNumber.length));
                    const currentNumber = intNumber.slice(-Math.min(groupKey.length, intNumber.length));
                    // 比较末尾部分
                    return groupNumber == currentNumber;
                }
            });

            // 如果有能匹配上的数据
            if (groupKey) {
                map[groupKey] = [...map[groupKey], ...data[key]];
            } else {
                map[key] = data[key];
            }
        }
        // 小于等于5位时，不进行匹配
        else {
            map[key] = data[key];
        }
    }

    let res = [];
    Object.keys(map).forEach((key) => {
        // 过滤最新的信息、时间
        const filter = map[key].length > 0 ? map[key].sort((a, b) => b.date - a.date) : [];
        // 最新的信息
        const content = filter.length > 0 ? filter[0].content : '';
        // 最新的信息日期
        const date = filter.length > 0 ? filter[0].date : null;
        // 所有信息的id
        const ids = map[key].map((e) => e.id);
        // 短信状态
        const status = filter.length > 0 ? filter[0].status : '';

        res.push({
            [property]: key,
            data: map[key].map((e) => {
                return {
                    ...e,
                    content: he.decode(e.content),
                    date: timestampToTime(e.date)
                };
            }),
            count: map[key].length,
            content: he.decode(content),
            date: timestampToTime(date),
            ids: ids.join(','),
            haveUnread: map[key].some((e) => e.status == '0'),
            status
        });
    });
    return res;
};

/**
 * 将时间戳转为时间格式
 * @param {*} timestamp 时间戳
 * @returns 格式化后的时间
 */
const timestampToTime = (timestamp) => {
    if (timestamp) {
        if (timestamp.length == 12) {
            const time = '20' + timestamp;
            const fTime = String(time).substring(0, 4) + '/' + String(time).substring(4, 6) + '/' + String(time).substring(6, 8) + ' ' + String(time).substring(8, 10) + ':' + String(time).substring(10, 12) + ':' + String(time).substring(12, 14);
            return fTime;
        } else {
            return dayjs(timestamp).format('YYYY/MM/DD HH:mm:ss');
        }
    }
    return timestamp;
};

/**
 * 将分好组的数据的手机号与 phonebook_source 中的手机号进行比对，增加姓名
 * @param {*} data1 分好组的数据
 * @param {*} data2 phonebook_source 中的 phonebook_list
 * @returns
 */
const filterName = (data1, data2) => {
    let data = [];
    if (data2.length <= 0) {
        for (const r of data1) {
            r.name = '';
            data = data.concat(r);
        }
    } else {
        for (const r of data1) {
            for (const i of data2) {
                console.log('分组后data1中遍历r:', r.number.length);
                console.log('分组后data2:', data2);
                console.log('分组后data2中遍历i:', i);
                if (r.number.length > 5 && i.number.length > 5) {
                    // 去除所有非数字符号 、 去除前缀0
                    const intNumberByI = String(i.number.replace(/\D/g, '').replace(/^0+/, ''));
                    const intNumberByR = String(r.number.replace(/\D/g, '').replace(/^0+/, ''));

                    // 获取号码末尾 短的则获取全部 长的根据短的长度获取
                    const groupNumber = intNumberByR.slice(-Math.min(intNumberByR.length, intNumberByI.length));
                    const currentNumber = intNumberByI.slice(-Math.min(intNumberByR.length, intNumberByI.length));

                    if (groupNumber == currentNumber) {
                        r.name = he.decode(i.name);
                        r.isPhoneBook = true;
                        break;
                    } else {
                        r.name = r.number;
                        r.isPhoneBook = false;
                    }
                } else if (r.number == i.mobilePhone) {
                    r.name = he.decode(i.name);
                    r.isPhoneBook = true;
                    break;
                } else {
                    r.name = r.number;
                    r.isPhoneBook = false;
                }
            }
            data = data.concat(r);
        }
    }
    return data;
};

/**
 * 判断字符串是否包含中文
 */
export const isChinese = (str) => {
    let pattern = new RegExp('[\u4E00-\u9FA5]+');
    if (pattern.test(str)) {
        return true;
    }
    return false;
};

/**
 * 判断字符串是否> 127的 算ucs2  变成70;<= 127  GSM   140
 */
export const isucs2_old = (str) => {
    for (let i = 0; i < str.length; i++)
        if (str.charCodeAt(i) > 127) {
            return true;
        }
    return false;
};

export const isucs2 = (str) => {
    //Array with "The 7 bit defaultalphabet"
    let sevenbitdefault = new Array(
        '@',
        '£',
        '$',
        '¥',
        'è',
        'é',
        'ù',
        'ì',
        'ò',
        'Ç',
        '\n',
        'Ø',
        'ø',
        '\r',
        'Å',
        'å',
        '\u0394',
        '_',
        '\u03a6',
        '\u0393',
        '\u039b',
        '\u03a9',
        '\u03a0',
        '\u03a8',
        '\u03a3',
        '\u0398',
        '\u039e',
        '€',
        'Æ',
        'æ',
        'ß',
        'É',
        ' ',
        '!',
        '"',
        '#',
        '¤',
        '%',
        '&',
        "'",
        '(',
        ')',
        '*',
        '+',
        ',',
        '-',
        '.',
        '/',
        '0',
        '1',
        '2',
        '3',
        '4',
        '5',
        '6',
        '7',
        '8',
        '9',
        ':',
        ';',
        '<',
        '=',
        '>',
        '?',
        '¡',
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z',
        'Ä',
        'Ö',
        'Ñ',
        'Ü',
        '§',
        '¿',
        'a',
        'b',
        'c',
        'd',
        'e',
        'f',
        'g',
        'h',
        'i',
        'j',
        'k',
        'l',
        'm',
        'n',
        'o',
        'p',
        'q',
        'r',
        's',
        't',
        'u',
        'v',
        'w',
        'x',
        'y',
        'z',
        'ä',
        'ö',
        'ñ',
        'ü',
        'à'
    );

    let flag_str = false;
    for (let i = 0; i < str.length; i++) {
        let flag_char = false;
        for (let j = 0; j < sevenbitdefault.length; j++) {
            if (sevenbitdefault[j] == str.charAt(i)) {
                flag_char = true;
                break;
            }
        }

        if (!flag_char) {
            flag_str = true;
            break;
        }
    }
    return flag_str;
};

/**
 * @description 校验SMS中的手机格式
 */
export const isValidSMSPhone = (phone) => {
    let regex = new RegExp('^[+]?[0-9]+$');
    return regex.test(phone);
};

/**
 * @description 获取电话本名称有效长度
 */
export const getValidPhoneNameLength = (nameStr) => {
    if (isAsciiRange(nameStr)) {
        return 14;
    } else {
        return 6;
    }
};

/**
 * @description 校验电话本名称, 获取字符串长度
 */
export const getPhoneNameLength = (nameStr) => {
    let length = 0;
    for (let i = 0; i < nameStr.length; i++) {
        const charCode = nameStr.charCodeAt(i);
        if (charCode > 0 || charCode <= 127) {
            length += 1;
        } else {
            if (charCode > 0x10000) {
                length += 2;
            } else {
                length += 1;
            }
        }
    }
    return length;
};

/**
 * @description 校验所有字符是否在 ascii 码范围
 * @param str 字符串
 * @param min ascii 范围最小值
 * @param max ascii 范围最大值
 */
export const isAsciiRange = (str, min = 0, max = 127) => {
    for (let i = 0; i < str.length; i++) {
        const charCode = str.charCodeAt(i);
        if (charCode < min || charCode > max) {
            return false; // 发现一个字符不在 ASCII 码范围内，返回 false
        }
    }
    return true; // 所有字符都在 ASCII 码范围内
};
